/**
 * 定义itfreer.form.safe模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义运维模块
	 */
	var itfreerformsafeModule = angular.module('itfreer.form.safe', ['itfreer.form.core']);

	/**
	 * 定义表单变量
	 */
	itfreerformsafeModule.value('$domainObject',{
		// 选择的字典域
		selectedDomain : {},
		// 选择的字典域
		selectedDomainRow : {},
		// 字典表名称
		domainTableName : "",
		// 域名称控制
		isAddDomain : {},
		// 表单名称
		formObjectName : ""
	});

	/**
	 * 定义表单数据访问服务
	 */
	itfreerformsafeModule.factory('$itfreer_form_safe', 
		function($rootScope, $http, $domainObject, $itfreer_core, 
			$itfreerHttp, $formObject, $itfreer_form_core) {
		$itfreer_form_safe = {
			// 清除角色缓存
			clearRoleCache : function(){
				$itfreerHttp.clearRoleCache(
					function(data){
						$.messager.alert('系统提示', '应用成功。请相关用户重新登录系统！');
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '应用失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '应用失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '应用失败！原因：请求超时！');
						}
					}
				);
			},

			// 清除工作时间设置缓存
			clearWorkDayCache : function(){
				$itfreerHttp.clearWorkDayCache(
					function(data){
						$.messager.alert('系统提示', '应用成功！');
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
								$.messager.alert('系统提示', '应用失败！原因：'+xhr.responseText);
						}else{
							$.messager.alert('系统提示', '应用失败！原因：请求超时！');
						}
					}
				);
			},

			// 重新载入委托信息设置缓存
			reloadWt : function(){
				$itfreerHttp.reloadWt(
					function(data){
						$.messager.alert('系统提示', '委托成功！请重新登录系统');
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
								$.messager.alert('系统提示', '委托失败！原因：'+xhr.responseText);
						}else{
							$.messager.alert('系统提示', '委托失败！原因：请求超时！');
						}
					}
				);
			},

			// 停止使用角色委托
			enableRoleWts : function(){
				var delOk = confirm('确定取消选择的角色委托?');
				if(!delOk){
					return;
				}
				var rows = $formObject.user.editList.checkedRows;
				if(rows==null){
					return;
				}
				debugger;
				var keys = $formObject.user.keyField+":in";
				var values = "";
				var dRows = [];
				rows.forEach(function(e){  
					if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
						if (typeof (e[$formObject.user.keyField]) == 'string'){
							values += "'"+e[$formObject.user.keyField] + "',";
						}else{
							values += e[$formObject.user.keyField] + ",";
						}
						dRows.push(e);
					}
				});
				if(values!=""){
					values = values.substr(0, values.length-1);
					var rowMap = {};
					rowMap[keys] = values;
					$itfreerHttp.enableRoleWt(rowMap,
						function(data){
							$rootScope.$apply(function() {
								rows.forEach(function(e){  
									if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
										e["S_ISUSE"]="1";
									}
								});
							});
						}, 
						function(xhr){
							if(xhr.hasOwnProperty('responseText') 
									&& xhr.responseText!=null
									&& xhr.responseText!=''){
								if(xhr.responseText.length>300){
									alert('取消失败！原因：未授权！');
								}else{
									alert('取消失败！原因：'+xhr.responseText);
								}
							}else{
								alert('取消失败！原因：请求超时！');
							}
						}
					);
				}
			},

			// 修改密码
			savePassword : function() {
				$itfreerHttp.savePassword($formObject.password.oldPW, $formObject.password.newPW, $formObject.password.rnewPW,
					function(data){
						
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '修改密码失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '修改密码失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '修改密码失败！原因：请求超时！');
						}
					}
				);
			},

			// treeGirdName : 树Grid的名称
			initDomainPara : function(treeGirdName, keyField, idField, pIDField, orderField, treeJBField, treeIsChildField){
				var formName = "domainform";
				$formObject[formName] = {};
				$formObject[formName].treeGirdName = treeGirdName;
				$formObject[formName].keyField = keyField;
				$formObject[formName].orderField = orderField;
				$formObject[formName].idField = idField;
				$formObject[formName].pIDField = pIDField;
				// 树级别字段
				$formObject[formName].treeJBField = treeJBField;
				// 树是否叶子节点字段
				$formObject[formName].treeIsChildField = treeIsChildField;
			},
			
			// 添加新字典
			addNewDomain : function(){
				$domainObject.isAddDomain.value = true;
				var obj = {};
				var guid = $itfreer_core.getGUID();
				obj["DOMAINID"] = guid;
				obj[$formObject.isNew] = true;
				obj["_IS_DOMAIN_TRUE"] = true;
				// 默认表
				$domainObject.domainTableName = "DATA_DEFULATDOMAIN";
				$itfreer_form_core.setEditRow("domainform", obj);
			},
			
			// 添加顶级字典项
			addTopDomainItem : function(){
				$domainObject.isAddDomain.value = false;
				if($domainObject.selectedDomainRow.value==null
						|| !$domainObject.selectedDomainRow.value.hasOwnProperty("attributes")
						|| !$domainObject.selectedDomainRow.value.attributes){
					$.messager.alert('系统提示', '当前字典不可编辑！');
					return;
				}
				
				var obj = {};
				var guid = $itfreer_core.getGUID();
				obj["DOMAINID"] = guid;
				obj[$formObject.isNew] = true;
				obj["_IS_DOMAIN_TRUE"] = true;
				
				var domainName = $domainObject.selectedDomain.value;
				var msgs = domainName.split(":");
				obj["DOMAINNAME"] = msgs[1];
				$domainObject.domainTableName = msgs[0];
				
				$itfreer_form_core.setEditRow("domainform", obj);
			},
			
			// 添加下级字典项
			addNextDomainItem : function(){
				$domainObject.isAddDomain.value = false;
				if($domainObject.selectedDomainRow.value==null
						|| !$domainObject.selectedDomainRow.value.hasOwnProperty("attributes")
						|| !$domainObject.selectedDomainRow.value.attributes){
					$.messager.alert('系统提示', '当前字典不可编辑！');
					return;
				}
				
				var treeGridControl = $('#'+$formObject["domainform"].treeGirdName);
				var selectedNode = treeGridControl.treegrid('getSelected');
				if(selectedNode==null){
					$.messager.alert('系统提示', '请选择一个父节点！');
					return;
				}
				
				var row = jQuery.extend(true, {}, $formObject["domainform"].defaultObject);
				row[$formObject.isNew]=true;
				row[$formObject["domainform"].pIDField] = selectedNode[$formObject["domainform"].idField];
				var guid = $itfreer_core.getGUID();
				row["DOMAINID"] = guid;
				row["_IS_DOMAIN_TRUE"] = true;
				
				row["ISUSER"] = '1';
				row["ISEDIT"] = '1';
				row['DOMAINCODE'] = $formObject['domainform'] && $formObject['domainform'].curOldRow && $formObject['domainform'].curOldRow.DOMAINCODE;
				
				var domainName = $domainObject.selectedDomain.value;
				var msgs = domainName.split(":");
				row["DOMAINNAME"] = msgs[1];
				$domainObject.domainTableName = msgs[0];
				
				$itfreer_form_core.setEditRow("domainform", row);
			},
			
			// 编辑字典项
			editDomainItem : function(){
				$domainObject.isAddDomain.value = false;
				if($domainObject.selectedDomainRow.value==null
						|| !$domainObject.selectedDomainRow.value.hasOwnProperty("attributes")
						|| !$domainObject.selectedDomainRow.value.attributes){
					$.messager.alert('系统提示', '当前字典不可编辑！');
					return;
				}
				
				var treeGridControl = $('#'+$formObject["domainform"].treeGirdName);
				var row = treeGridControl.treegrid('getSelected');
				if(row==null){
					$.messager.alert('系统提示', '请选择一个父节点！');
					return;
				}
				
				row["_IS_DOMAIN_TRUE"] = true;
				var domainName = $domainObject.selectedDomain.value;
				var msgs = domainName.split(":");
				row["DOMAINNAME"] = msgs[1];
				$domainObject.domainTableName = msgs[0];
				$itfreer_form_core.setEditRow("domainform", row);
			},
			
			delDomainItem : function(){
				if($domainObject.selectedDomainRow.value==null
						|| !$domainObject.selectedDomainRow.value.hasOwnProperty("attributes")
						|| !$domainObject.selectedDomainRow.value.attributes){
					$.messager.alert('系统提示', '当前字典不可编辑！');
					return;
				}
				
				var treeGridControl = $('#'+$formObject["domainform"].treeGirdName);
				var row = treeGridControl.treegrid('getSelected');
				if(row==null){
					$.messager.alert('系统提示', '请选择一个父节点！');
					return;
				}
				
				$.messager.confirm("操作确认", '确定删除此记录?', function(r){
					if(r){
						row["_IS_DOMAIN_TRUE"] = true;
						var domainName = $domainObject.selectedDomain.value;
						var msgs = domainName.split(":");
						row["DOMAINNAME"] = msgs[1];
						$domainObject.domainTableName = msgs[0];
						$itfreer_form_core.delTreeSelectedRows("domainform", $domainObject.domainTableName, row);
					}
				});
			},
			
			// 保存字典域
			saveDomain : function(successFunction, failFunction){
				$itfreer_form_core.save("domainform", $domainObject.domainTableName,null, null, null, null, successFunction, failFunction);
			},
			
			// 初始化字典数据
			initDomainData : function(){
				var domainName = $domainObject.selectedDomain.value;
				if(!domainName){
					return;
				}

				var msgs = domainName.split(":");
				$itfreerHttp.getDomainsEx(msgs[0], msgs[1], true, function(treedata){
					if(treedata==null){
						treedata=[];
					}
					var treeGridControl = $('#'+$formObject["domainform"].treeGirdName);
					treeGridControl.treegrid('loadData', treedata);
				},
				function(xhr){
					if(xhr.hasOwnProperty('responseText') 
							&& xhr.responseText!=null
							&& xhr.responseText!=''){
						if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
							$.messager.alert('系统提示', '字典获取失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
						}else{
							$.messager.alert('系统提示', '字典获取失败！原因：'+xhr.responseText);
						}
					}else{
						$.messager.alert('系统提示', '字典获取失败！原因：请求超时！');
					}
				});
			},

			/**
			 * 人员选择组件，并增加去除重复
			 */
			assignmentUserChild : function(editRow, childTableName, selectedRows) {
				if(selectedRows){
					if(!editRow.childValues){
						editRow.childValues = {};
					}
					var currentRows = editRow.childValues[childTableName];
					selectedRows.forEach(function(e){
						var row = jQuery.extend(true, {}, e);
						row[$formObject.isNew] = true;
						row["GUID"]="";
						var isNotExist=true;
						currentRows.forEach(function(e){
							var curtRow = jQuery.extend(true, {}, e);
							if(curtRow['S_USERID']==row['S_USERID']){
								isNotExist=false;
							}
						});
						if(isNotExist){
						 	editRow.childValues[childTableName].push(row);
						}
					});
				}
			}
		};
		for(f in $itfreer_form_safe){
			$rootScope[f] = $itfreer_form_safe[f];
		}
		$rootScope.domainObject = $domainObject;
		return $itfreer_form_safe;
	}); 

	/**
	 * 委托状态
	 */
	itfreerformsafeModule.filter("asRoleWtState", function () {
	    return function (input) {
	    	if(input==1){
	    		return "已结束";
	    	}else{
	    		return "委托中";
	    	}
	    };
	});
	
	/* 
	 * 加载服务器
	 */
	itfreerformsafeModule.run(function($rootScope, $itfreer_form_safe, $domainObject) {
	  	
	});
}(window, angular));